Page({
    data: {
      // 8个商品分类
      categories: [
        { name: "全部商品", tag: "all" }, 
        { name: "日常清洁", tag: "日常清洁" },
        { name: "美白焕亮", tag: "美白焕亮" },
        { name: "敏感护理", tag: "敏感护理" },
        { name: "儿童专属", tag: "儿童专属" },
        { name: "正畸专用", tag: "正畸专用" },
        { name: "口腔护理", tag: "口腔护理" },
        { name: "口腔喷雾", tag: "口腔喷雾" },
        { name: "牙齿养护", tag: "牙齿养护" }
      ],
      currentTab: 0, // 当前选中的Tab索引
      allProducts: [
        // 模拟商品数据（实际可从后端获取）
        { id: 1, category: "健康优选", tag: "日常清洁", imageUrl: "https://picsum.photos/300/300?random=101", score: 4.5, Product_Details: "深层清洁牙膏，有效去除牙菌斑...", now_price: 129.00, old_price: 169.00 },
        { id: 2, category: "限时特惠", tag: "日常清洁", imageUrl: "https://picsum.photos/300/300?random=102", score: 4.8, Product_Details: "软毛牙刷套装，呵护牙龈健康...", now_price: 88.00, old_price: 128.00 },
        { id: 3, category: "新品上市", tag: "美白焕亮", imageUrl: "https://picsum.photos/300/300?random=103", score: 5.0, Product_Details: "美白牙贴，一周见效...", now_price: 258.00, old_price: 299.00 },
        { id: 4, category: "热销爆款", tag: "美白焕亮", imageUrl: "https://picsum.photos/300/300?random=104", score: 4.2, Product_Details: "美白漱口水，持久清新口气...", now_price: 199.00, old_price: 239.00 },
        { id: 5, category: "健康优选", tag: "敏感护理", imageUrl: "https://picsum.photos/300/300?random=105", score: 4.7, Product_Details: "抗敏感牙膏，缓解牙齿敏感...", now_price: 369.00, old_price: 399.00 },
        { id: 6, category: "限时特惠", tag: "敏感护理", imageUrl: "https://picsum.photos/300/300?random=106", score: 4.3, Product_Details: "敏感牙龈专用牙刷...", now_price: 59.00, old_price: 89.00 },
        { id: 7, category: "新品上市", tag: "儿童专属", imageUrl: "https://picsum.photos/300/300?random=107", score: 4.9, Product_Details: "儿童防蛀牙膏，水果口味...", now_price: 159.00, old_price: 189.00 },
        { id: 8, category: "热销爆款", tag: "儿童专属", imageUrl: "https://picsum.photos/300/300?random=108", score: 4.6, Product_Details: "儿童卡通牙刷，让孩子爱上刷牙...", now_price: 229.00, old_price: 269.00 },
        { id: 9, category: "健康优选", tag: "正畸专用", imageUrl: "https://picsum.photos/300/300?random=109", score: 4.4, Product_Details: "正畸蜡，缓解矫正器磨嘴...", now_price: 89.00, old_price: 109.00 },
        { id: 10, category: "限时特惠", tag: "正畸专用", imageUrl: "https://picsum.photos/300/300?random=110", score: 4.6, Product_Details: "正畸牙刷，清洁矫正器缝隙...", now_price: 69.00, old_price: 99.00 },
        { id: 11, category: "新品上市", tag: "口腔护理", imageUrl: "https://picsum.photos/300/300?random=111", score: 4.8, Product_Details: "口腔护理凝胶，预防口腔问题...", now_price: 199.00, old_price: 229.00 },
        { id: 12, category: "热销爆款", tag: "口腔喷雾", imageUrl: "https://picsum.photos/300/300?random=112", score: 4.7, Product_Details: "口气清新喷雾，持久去异味...", now_price: 129.00, old_price: 159.00 },
        { id: 13, category: "健康优选", tag: "牙齿养护", imageUrl: "https://picsum.photos/300/300?random=113", score: 4.9, Product_Details: "牙齿养护精华液，强化牙釉质...", now_price: 269.00, old_price: 299.00 }
      ],
      currentProducts: [] // 当前Tab下的商品列表
    },

    // 新增：跳转到搜索页面
  goToSearchPage: function() {
    wx.navigateTo({
      url: '/pages/business/search/search',
    })
  },

    //跳转到购物车界面
    goToShoppingCart(){
        wx.navigateTo({
          url: '/pages/business/ShoppingCart/ShoppingCart',
        })
    },
  
    onLoad: function () {
      // 页面加载时默认选中第一个Tab
      this.switchTab({ currentTarget: { dataset: { index: 0 } } });
    },
  
    // 2. 修改 switchTab 函数逻辑
  switchTab: function (e) {
    const index = e.currentTarget.dataset.index;
    const selectedCategory = this.data.categories[index];

    // 判断是否选中了“全部商品”
    if (selectedCategory.tag === 'all') {
      // 如果是“全部商品”，则获取打乱后的所有商品
      const shuffledProducts = this.shuffleArray([...this.data.allProducts]);
      this.setData({
        currentTab: index,
        currentProducts: shuffledProducts
      });
    } else {
      // 其他分类，按原逻辑筛选
      const tag = selectedCategory.tag;
      const products = this.data.allProducts.filter(item => item.tag === tag);
      this.setData({
        currentTab: index,
        currentProducts: products
      });
    }
  },

  /**
   * 1. 获取当前活跃的分类标签
   * 2. 根据标签筛选出对应的商品列表
   * 3. 对筛选出的列表进行打乱
   * 4. 更新 currentProducts 数据
   */
  onPullDownRefresh: function () {
    const that = this;
    const currentCategoryTag = this.data.categories[this.data.currentTab].tag;
  
    // 1. 立即将 currentProducts 清空，强制小程序销毁所有列表项
    this.setData({
      currentProducts: []
    });
  
    // 模拟网络请求延迟
    setTimeout(() => {
      let productsToShuffle;
  
      // 根据当前标签筛选商品
      if (currentCategoryTag === 'all') {
        productsToShuffle = that.data.allProducts;
      } else {
        productsToShuffle = that.data.allProducts.filter(item => item.tag === currentCategoryTag);
      }
  
      // 对筛选出的商品列表进行打乱
      const shuffledProducts = that.shuffleArray(productsToShuffle);
  
      // 2. 在清空之后，再用新的打乱数组更新 currentProducts
      // 使用 setTimeout(fn, 0) 确保这一步在清空操作之后执行
      setTimeout(() => {
        that.setData({
          currentProducts: shuffledProducts
        }, () => {
          // 数据更新完成后，停止下拉刷新动画
          wx.stopPullDownRefresh();
        });
      }, 0);
  
    }, 500);
  },

  /**
   * 辅助函数：使用 Fisher-Yates 洗牌算法打乱数组
   */
  shuffleArray: function(array) {
    // 1. 使用 slice 创建原数组的浅拷贝，确保我们不会修改原始数据
    const newArray = array.slice(); 
    
    // 2. 在新数组上进行洗牌操作
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      // ES6 的解构赋值交换元素
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    
    // 3. 返回打乱后的新数组
    return newArray;
  },
  
    // 搜索功能（保留原逻辑）
    onSearch(e) {
      const keyword = e.detail.value;
      if (keyword) {
        console.log("搜索内容：", keyword);
      } else {
        wx.showToast({ title: "请输入搜索内容", icon: "none" });
      }
    },
  
    onInput(e) {
      const keyword = e.detail.value;
      console.log("实时输入：", keyword);
    },
  
    onCancel() {
      console.log("取消搜索");
    },
  
    // 跳转到商品详情页
    goToShoping: function (e) {
    //   const productId = e.currentTarget.dataset.productId;
    //   console.log('准备跳转到商品', productId, '的详情页');
      // 实际项目中可跳转：wx.navigateTo({ url: `/pages/productDetail/productDetail?id=${productId}` });
      wx.navigateTo({ url: "/pages/business/shoping/shoping"});
    },
  
    // 悬浮AI助手事件
    onAiAction(e) {
      const { action } = e.detail
      switch (action) {
        case 'chat':
          wx.navigateTo({ url: '/pages/ai-chat/ai-chat' })
          break
        case 'help':
          wx.showModal({ title: '帮助', content: 'AI助手可帮您解答牙齿健康问题' })
          break
      }
    }
  });